package pers.cz.netty.handle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.cz.config.JefConfiguration;
import pers.cz.netty.config.ServerNettyConfigItem;

/**
 * @program: PostGirl-panent
 * @description: 超时检测
 * @author: Cheng Zhi
 * @create: 2022-10-05 08:13
 **/
public class ServerIdleStateHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(ServerIdleStateHandler.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            int timeOut = JefConfiguration.getInt(ServerNettyConfigItem.SERVER_HEART_READ_TIME, 15);
            if (state == IdleState.READER_IDLE) {
                log.debug("====================================================================================");
                log.debug("| !!! Heart Read timeout !!! client may be offline, connection will be closed soon. |");
                log.debug("| The timeout of the current configuration is {}s                                   |",timeOut);
                log.debug("======================================================================================");
                ctx.disconnect();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
